<template>
    <div class="btn">
      <el-button @click="show" :disabled="props.disabled">{{ props.label || "选择标签" }}</el-button>
    </div>
    <div class="zw-el-tags">
      <el-tag class="tagsItem" v-for="(item, index) in labels" :key="item.name" 
        @close="handleClose(item, index)" :closable="!props.disabled">
        {{ item.name }}
      </el-tag>
    </div>
   

    <BatchLabel ref="BatchLabelRef" @save="getLabelFun" />

</template>
<script setup lang="tsx">
import { reactive, ref, watch, computed, nextTick } from 'vue'
import BatchLabel from '@/components/BatchLabel.vue'

const BatchLabelRef = ref<any>(null)

interface Props {
  modelValue: string|string[],
  creators: any[],
  multiple: boolean,
  disabled: boolean,
  label: string
}
const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    creators: ()=>[],
    multiple: false,
    disabled: false,
    label: ''
})

let labels = reactive<any[]>([])

const emit = defineEmits(['update:modelValue'])

const updateValue = (value:any)=>{
  emit('update:modelValue', value)
}

const getLabelFun = (label: any):void => {
  console.log('label - - -   ', label)
  labels.splice(0)
  labels.push(...label.data)
  console.log('labels - - -   ', labels)
  if(props.multiple){
    updateValue(mapID(labels))
  }else{
    updateValue(labels[0]?.external_shop_id)
  }
}

const show = () => {
  BatchLabelRef.value.title = '选择标签'
  BatchLabelRef.value.chooseDataArr.value = labels
  BatchLabelRef.value.hasConditiion = false
  BatchLabelRef.value.dialogData.labelChooseType = 2
  BatchLabelRef.value.dialogVisible = true
}

const handleClose = (item: any, index: number) => {
  labels.splice(index, 1)
  // BatchLabelRef.value.chooseDataArr = labels
  if(props.multiple){
    updateValue(mapID(labels))
  }else{
    updateValue(labels[0]?.id ?? '')
  }
}

const mapID = (arr:any)=>{
  if(!!arr?.length){
    return arr.map((item:any) => item.id)
  }else{
    return []
  }
}

watch(()=>props.creators, (val)=>{
  labels.splice(0)
  if(val?.length){
    labels.push(...val)
    updateValue(mapID(val))
    // DepartRef.value.departVisble = false
    // DepartRef.value.selectedMember = val
  }else{
    updateValue([])
    // DepartRef.value.selectedMember = []
  }
  nextTick(()=>{
    BatchLabelRef.value.chooseDataArr.value = labels.map((item:any)=>{
      item.check = true
      return item
    })
  })
  console.log('labels - - -   ', labels)
}, {deep: true, immediate: true})



</script>
<style scoped lang="scss">
  .store_item {
    margin-right: 6px;
  }
  .btn {
    margin-bottom: 16px;
  }
  .tagsItem {
    margin-right: 10px;
  }
</style>
